package joyi.train.employee.service.impl;

import j.framework.core.ServiceContext;
import j.util.StringUtils;
import j.util.jdbc.RowMapper;
import j.util.pkgenerator.PG;
import joyi.train.employee.domain.Position;
import joyi.train.employee.service.PositionService;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * Created by WY2015092804 on 2015/10/20.
 */
public class PositionServiceImpl implements PositionService {
    @Override
    public Position getPosition(ServiceContext serviceContext) {
        String positionId = serviceContext.params.getString("positionId");
        if (StringUtils.isNotEmpty(positionId)) {
            return serviceContext.getJdbcTemplate().queryForDomain("select * from cw_Position where positionId =? ", new RowMapper<Position>() {
                @Override
                public Position mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Position position = new Position();
                    position.setPositionId(rs.getString("positionId"));
                    position.setNote(rs.getString("note"));
                    position.setPositionName(rs.getString("positionName"));
                    return position;
                }
            }, positionId);
        }
        return null;
    }

    @Override
    public String delPosition(ServiceContext serviceContext) {
        String positionId = serviceContext.params.getString("positionId");
        if (StringUtils.isNotEmpty(positionId)) {
            int count = serviceContext.getJdbcTemplate().queryForInt("select count(1) from cw_Employee where positionId = ?", positionId);
            if (count > 0) {
                serviceContext.actionResult.add("err", "有员工是此职位");
                return null;
            } else {
                Position position = new Position();
                position.setPositionId(positionId);
                serviceContext.getJdbcTemplate().delete(position);
                return "删除成功";
            }
        }
        serviceContext.actionResult.add("err", "你没有指定要删除的职位");
        return null;
    }
    @Override

    public void saveOrUpdatePosition(ServiceContext serviceContext) {
        Position position = serviceContext.getBean(Position.class);
        if (StringUtils.isNotEmpty(position.getNote())){
            position.setNote(position.getNote().trim());
        }
        if (StringUtils.isNullOrEmpty(position.getPositionId())) {
            position.setPositionId(PG.getNext("POS"));
            position.setAddedTime(new Date());
            position.setAddedUserId(serviceContext.getUser().getUserId());
            serviceContext.getJdbcTemplate().insert(position);
        } else {
            serviceContext.getJdbcTemplate().update(position);
        }
    }
}
